<template>
	<view class="test-question">
		<!-- 自定义导航栏 -->
		<view class="menu-btn-area" :style="{height: `${navHeight}px`,paddingTop: `${navTop}px`}">
			<uni-nav-bar backgroundColor="#F1F4FF" style="width: 100vw;" left-icon="left" :title="title"
				@clickLeft="handleLeftClick" />
		</view>
		<!-- 头部 -->
		<view class="header page-padding" :style="{ marginTop:`${navHeight+navTop+16}px`}">
			<view v-if="!isReviewing" class="row1">
				<view class="left">答题时间: {{formatTime(spentTime)}}</view>
				<view class="right" @click="openConfirmPopup">
					<view class="circle"></view>
					<view class="text">提交</view>
				</view>
			</view>
			<view class="row2">
				<uv-line-progress v-if="!isReviewing" height="16rpx" activeColor="#7491FE" :percentage="progress">
					<text class="uv-percentage-slot">{{selectedNum}}</text>
				</uv-line-progress>
				<view v-if="!isReviewing" class="progress">
					{{selectedNum}}/{{questionList.length}}
				</view>
				<view v-if="!isReviewing && !questionList[currentQuestionIndex]?.classifyFirstId" class="container"
					@click="openConditionPopup">
					<image class="img" src="../../static/test-question/total.png"></image>
				</view>
			</view>
		</view>
		<!-- 题目详情 -->
		<question-detail :detail="questionList[currentQuestionIndex]" :currentIndex="currentQuestionIndex"
			:questionListParams="questionListParams" :isReviewing="isReviewing" :questionAnswer="questionAnswer"
			@lastClick="handleLastClick" @nextClick="handleNextClick" @feedbackBtnClick="onFeedbackBtnClick"
			@getParams="getQuestionParams" @collectClick="collectClick" :hide="hide" :getAnswer="getAnswer" />
		<!-- 交卷popup层 -->
		<ConfirmPopup ref="confirmPopupRef" :undoneCount="undoneCount" :doneCount="doneCount"
			@submitClck="handleSubmitClick" />
		<!-- 答题情况 -->
		<ConditionPopup ref="conditionPopupRef" :isReviewing="isReviewing" :isSelected="isSelected"
			:questionList="questionList" @toQuestionDetail="toQuestionDetail" />
		<!-- 题目反馈 -->
		<FeedbackPopup ref="feedbackPopupRef" :typeList="feedbackTypeList" @submitFeedback="onSubmitFeedback" />
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		storeToRefs
	} from 'pinia'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import useMenuButton from '@/hook/use-menu-button';
	import {
		formatTime
	} from '@/utils/format.js'
	import {
		useBaseQuestionStore,
		useTestQuestionStore
	} from '@/store';
	import ConfirmPopup from './cpns/confirm-popup/confirm-popup.vue'
	import FeedbackPopup from './cpns/feedback-popup/feedback-popup.vue'
	import ConditionPopup from './cpns/condition-popup/condition-popup.vue'

	// 获取胶囊信息
	const [navHeight, navTop] = useMenuButton()
	// 标题
	const title = ref('')
	// 答题时间
	const spentTime = ref(0)
	// 多道题的参数集合
	const questionListParams = ref([])
	// 提交答题弹出层的实例
	const confirmPopupRef = ref()
	// 答题详情弹出层的实例
	const conditionPopupRef = ref()
	// 题目反馈弹出层的实例
	const feedbackPopupRef = ref()
	// 计时器
	let timer

	// 获取仓库数据
	const testQuestionStore = useTestQuestionStore()
	const baseQuestionStore = useBaseQuestionStore()
	const {
		questionList,
		currentQuestionIndex,
		isReviewing,
		questionAnswer,
		isCorrectList,
		feedbackTypeList
	} = storeToRefs(testQuestionStore)
	const {
		questionParams,
		flag: type,
	} = storeToRefs(baseQuestionStore)

	const hide = ref(false)
	onLoad((options) => {
		// 根据title参数动态修改标题
		title.value = decodeURIComponent(options.title)
		if (options.status) {
			hide.value = true
		} else {
			hide.value = false
		}
		// 启动计时器
		timer = setInterval(() => {
			spentTime.value += 1
		}, 1000)
	})

	onUnload(() => {
		clearInterval(timer)
	})

	onMounted(() => {
		// 初次进来获取题目反馈类型数据
		testQuestionStore.getFeedbackTypeListAction()
	})

	// 计算出当前答完题的数量
	const selectedNum = computed(() => {
		// 过滤出答案的个数不为0的项
		const newArr = questionListParams.value.filter(item => item.userAnswer && item.userAnswer.length > 0)
		return newArr.length
	})
	// 计算出进度
	const progress = computed(() => {
		return (selectedNum.value / questionList.value.length) * 100
	})
	// 计算出当前题目是否选择了答案【答题】  或者 对错情况【解析题目】
	const isSelected = computed(() => {
		return (index) => {
			if (isReviewing.value) {
				return isCorrectList.value[index]
			} else {
				return questionListParams.value[index]?.userAnswer.length > 0
			}
		}
	})
	// 计算未答题目数量
	const undoneCount = computed(() => {
		const doneList = questionListParams.value.filter(item => item.userAnswer.length > 0)
		return questionList.value.length - doneCount.value
	})
	// 计算已答题目数量
	const doneCount = computed(() => {
		const doneList = questionListParams.value.filter(item => item.userAnswer.length > 0)
		return doneList.length
	})

	// 返回上一个页面
	const handleLeftClick = () => {
		uni.navigateBack({
			delta: 1
		})
	}

	// 子传父：上一题和下一题
	const handleLastClick = () => {
		if (currentQuestionIndex.value >= 1) {
			testQuestionStore.currentQuestionIndex--
			return
		}
		uni.showToast({
			icon: "error",
			title: '已经是第1题了哦'
		})
	}
	const handleNextClick = () => {
		if (currentQuestionIndex.value <= questionList.value.length - 2) {
			testQuestionStore.currentQuestionIndex++
			return
		}
		uni.showToast({
			icon: "error",
			title: '已经没题了哦'
		})
	}

	// 子传父：获取答案提交带来的参数
	const getQuestionParams = (params, index) => {
		questionListParams.value[index] = params
		console.log(questionListParams.value);
	}
	const getAnswer = () => {
		return questionListParams.value
	}

	// 打开popup查看答题情况
	const openConditionPopup = () => {
		conditionPopupRef.value.open()
	}

	// 点击答题情况里面的某个题目序号跳转到具体题目
	const toQuestionDetail = (index) => {
		testQuestionStore.currentQuestionIndex = index
		// 跳转完关闭popoup层
		conditionPopupRef.value.close()
	}

	// 打开题目提交popup
	const openConfirmPopup = () => {
		confirmPopupRef.value.open()
	}

	// 提交答题按钮
	const handleSubmitClick = () => {
		// 如果还有没做的题给用户提示
		if (undoneCount.value > 0) {
			uni.showModal({
				content: `您还有${undoneCount.value}道题没完成，请完成再提交`,
				success() {
					confirmPopupRef.value.close()
				}
			})
		} else {
			// 如果做完直接提交
			submitQuestion()
			confirmPopupRef.value.close()
		}
	}

	// 获取最终整理好的参数
	const submitQuestion = () => {
		const hasSelectedArr = questionListParams.value.filter(item => item.userAnswer.length > 0)
		// 初始化真正提交的参数，后续会修改里面的部分数据
		const paramsList = questionList.value.map(item => {
			return {
				classifyId: questionParams.value.classifyId,
				userId: uni.getStorageSync('userInfo')?.userId,
				isCorrect: 0,
				questionId: item.questionId,
				userAnswer: []
			}
		})
		// 修改部分参数，将答完题了的参数覆盖到参数列表里面
		paramsList.forEach(item => {
			hasSelectedArr.forEach(iitem => {
				if (iitem.questionId === item.questionId) {
					item.userAnswer = iitem.userAnswer
					item.isCorrect = iitem.isCorrect
				}
			})
		})
		const realParams = {
			list: paramsList,
			spentTime: spentTime.value,
			type: type.value,
			classifyId: questionParams.value.classifyId
		}
		// 提取答题前用户输入的答案
		const questionAnswer = paramsList.map(item => item.userAnswer)
		testQuestionStore.questionAnswer = questionAnswer
		// 提取答题前答案的对错
		const isCorrectList = paramsList.map(item => item.isCorrect)
		testQuestionStore.isCorrectList = isCorrectList
		console.log(questionAnswer, isCorrectList);
		testQuestionStore.reqSubmitQuestionAction(realParams)
		uni.redirectTo({
			url: "/pages/after-submit/after-submit"
		})
	}

	// 子传父：点击反馈按钮打开popup层
	const onFeedbackBtnClick = () => {
		feedbackPopupRef.value.open()
	}

	// 子传父：提交反馈按钮
	const onSubmitFeedback = (feedbackTypeId, detailCause) => {
		// 整理参数
		const questionId = questionList.value[currentQuestionIndex.value].questionId
		const userId = uni.getStorageSync('userInfo')?.userId
		const data = {
			userId,
			questionId,
			feedbackTypeId,
			detailCause
		}
		testQuestionStore.submitFeedbackAction(data)
	}

	// 子传父，收藏与取消收藏
	const collectClick = () => {
		// 当前题目
		const question = questionList.value[currentQuestionIndex.value]
		// 请求收藏或者取消收藏操作
		const data = {
			userId: uni.getStorageSync('userInfo')?.userId,
			questionId: question.questionId
		}
		testQuestionStore.reqQuestionCollectAction(data)
	}
</script>

<style lang="scss">
	page {
		background: $bg-color;
		box-sizing: border-box;
	}

	.uni-navbar--border {
		border-bottom-color: #cfcfcf !important;
	}

	.menu-btn-area {
		display: flex;
		align-items: center;
		background-color: #F1F4FF;
		padding-bottom: 10rpx;
		border-bottom: 2rpx solid #d0ccd1;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 99;
	}

	.uv-percentage-slot {
		font-size: 20rpx;
		margin-right: 20rpx;
	}

	.header {
		margin: 32rpx 0 30rpx 0;

		.row1 {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 10rpx;

			.left {
				color: $text-color;
				font-size: 24rpx;
			}

			.right {
				padding: 4rpx 14rpx;
				display: flex;
				align-items: center;
				background-color: $btn-bg-color;
				border-radius: 30rpx 0 0 30rpx;

				.circle {
					width: 26rpx;
					height: 26rpx;
					border-radius: 50%;
					margin-right: 10rpx;
					background-color: $second-primary-color;
					box-shadow: 2rpx 2rpx 20rpx $second-primary-color;
				}

				.text {
					color: $second-primary-color;
					font-size: 24rpx;
				}
			}
		}

		.row2 {
			display: flex;
			align-items: center;

			.progress {
				margin: 0 10rpx;
				font-size: 24rpx;
				color: $second-primary-color;
			}

			.container {
				background-color: $btn-bg-color;
				width: 46rpx;
				height: 46rpx;
				border-radius: 50%;
				display: flex;
				justify-content: center;
				align-items: center;

				.img {
					width: 26rpx;
					height: 26rpx;
				}
			}
		}
	}
</style>